package com.ht.web_vr_home_tour_backend.controller;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Api(tags = "图片数据控制器（图片属于对象，部分功能可以被对象控制器实现）")
@RestController
@RequestMapping("/api/img")
public class ImgController {

    byte[] cache = null;

    @GetMapping("/basic/avatar")
    public void getDefaultUserAvatar(HttpServletResponse response) {
        // TODO 需要重新实现
        File file = new File("C:/desk/头像.jpg");
        response.setContentType("image/jpeg");
        if (cache == null) {
            try (
                    ByteArrayOutputStream cacheOs = new ByteArrayOutputStream();
                    FileInputStream fileIs = new FileInputStream(file);
                    ) {
                IoUtil.copy(fileIs, cacheOs);
                cache = cacheOs.toByteArray();
            } catch (IOException e) {
                throw new IORuntimeException(e);
            }
        }

        try (
                ByteArrayInputStream cacheIs = new ByteArrayInputStream(cache);
                ServletOutputStream os = response.getOutputStream();
        ) {
            IoUtil.copy(cacheIs, os);
        } catch (IOException e) {
            throw new IORuntimeException(e);
        }
    }
}
